import HandleBtn from '@/components/HandleBar/btn';
import type { ActionType, ProColumns, ProFormInstance } from '@/components/Pro/';
import {
  ModalForm,
  ProForm,
  ProFormDependency,
  ProFormDigit,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProTable,
} from '@/components/Pro/';
// import { BATTERY_BOX_TYPE, DEVICE_TYPE, PCS_TYPE } from '@/dictionary';
import {
  deviceManagerControllerGetDeviceDetailByModel as getDeviceDetail,
  deviceManagerControllerGetDeviceModelList as getDeviceList,
} from '@/services/ess/deviceManager';
import {
  stationDeviceControllerAddDevice as add,
  stationDeviceControllerBatch as batchRemove,
  stationDeviceControllerDownloadExcel as downloadFile,
  stationDeviceControllerEditDevice as edit,
  stationDeviceControllerList as getList,
  stationDeviceControllerUploadExcel as uploadFile,
} from '@/services/ess/stationDevice';
import { downloadFetch } from '@/utils/downloadFile';
import { getIntl } from '@umijs/max';
import type { UploadProps } from 'antd';
import { Card, Flex, Image, message, Modal, Row, Space, Upload } from 'antd';
import React, { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { useIntl } from 'umi';
const { confirm } = Modal;

/**
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.StationDeviceReq) => {
  try {
    const res = await add({
      ...fields,
    });
    if (res.success) {
      message.success(getIntl().formatMessage({ id: 'global.addSuccessfully' }));
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.addFailedTips' }));
    return false;
  }
};

/**
 * @zh-CN 编辑节点
 * @param fields
 */
const handleEdit = async (fields: API.StationDeviceReq) => {
  try {
    const res = await edit({
      ...fields,
    });
    if (res.success) {
      message.success(getIntl().formatMessage({ id: 'global.editedSuccessfully' }));
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.editFailedTips' }));
    return false;
  }
};

const PreviewPic: React.FC<{
  value?: string;
}> = ({ value }) => {
  return <Image width={120} src={value} />;
};

const Table: React.FC<{
  id: number | string;
  disableEdit?: boolean;
}> = ({ id, disableEdit }, ref) => {
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<API.StationDeviceReq>({});
  const [selectedRowsState, setSelectedRows] = useState<API.StationDeviceReq[]>([]);
  const [disabled, setDisabled] = useState(false);
  const [readonly, setReadonly] = useState(false);
  const intl = useIntl();

  const DEVICE_TYPE = {
    3: {
      text: intl.formatMessage({
        id: 'systemManagement.deviceManagementMenu.pcs',
      }),
      order: 1,
    },
    1: {
      text: intl.formatMessage({
        id: 'systemManagement.deviceManagementMenu.Batterycabinet',
      }),
      order: 2,
    },
    2: {
      text: intl.formatMessage({
        id: 'systemManagement.deviceManagementMenu.Batteryboxs',
      }),
      order: 3,
    },
  };

  const PCS_TYPE = {
    '1': {
      text: intl.formatMessage({
        id: 'systemManagement.deviceManagementMenu.stringType',
      }),
    },
    '2': {
      text: intl.formatMessage({
        id: 'systemManagement.deviceManagementMenu.centralized',
      }),
    },
  };

  const BATTERY_BOX_TYPE = {
    1: {
      text: intl.formatMessage({
        id: 'systemManagement.supplementary.airCooler',
      }),
    },
    2: {
      text: intl.formatMessage({
        id: 'systemManagement.supplementary.liquidCooler',
      }),
    },
  };

  /**
   * @zh-CN 批量操作
   * @param type
   * @param selectedRows
   */
  function remove(record = selectedRowsState) {
    if (record.length < 1) {
      message.warning(intl.formatMessage({ id: 'global.leastOne' }));
      return;
    }
    if (disabled) return;
    setDisabled(true);
    confirm({
      title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
      content: '数据删除后将不可恢复，是否删除？',
      onOk: async () => {
        const res = await batchRemove(record.map((row) => row.id));
        if (res.success) {
          message.success(`删除成功！`);
          actionRef.current?.reloadAndRest?.();
        }
      },
      afterClose: () => {
        setDisabled(false);
      },
    });
  }

  useImperativeHandle(ref, () => ({
    remove,
    add: () => {
      setReadonly(false);
      setCurrentRow({});
      handleModalOpen(true);
    },
    selectedRowsState,
    customRequest: async (info) => {
      const form = new FormData();
      form.append('file', info.file);
      const res = await uploadFile(form, { ingoreErrorMsg: true });
      if (res?.success) {
        message.success(`${info.file.name} 文件导入成功`);
        actionRef?.current?.reloadAndRest?.();
        return;
      }
      const msg = res?.message;
      message.error(`${info.file.name} 文件导入失败 ${msg ? ',' + msg : ''}`);
    },
    download: () => {
      downloadFetch(downloadFile, { stationId: id });
    },
  }));

  const changeDeviceModal = async (deviceModel: string, deviceType: number) => {
    const res = await getDeviceDetail({
      deviceType: deviceType,
      deviceModel: deviceModel,
    });
    if (res.success) {
      const data = res?.data ?? {};
      data.pcsType = data?.pcsType?.toString();
      data.deviceType = data?.deviceType?.toString();
      formRef?.current?.setFieldsValue(data);
    }
  };

  const columns: ProColumns<API.StationDeviceReq>[] = [
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.SN' }),
      dataIndex: 'pageIndex',
      width: 50,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.Devicefactory' }),
      dataIndex: 'manufacturer',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.DeviceType' }),
      dataIndex: 'deviceType',
      valueEnum: DEVICE_TYPE,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.Devicemodel' }),
      dataIndex: 'deviceManagerName',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.siteAdministrationMenu.NumberOfDevices' }),
      dataIndex: 'deviceCount',
      hideInSearch: true,
    },
  ];

  if (!disableEdit) {
    columns.push({
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.operation' }),
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          <a
            key="edit"
            onClick={() => {
              setReadonly(false);
              handleModalOpen(true);
              setCurrentRow(record);
              changeDeviceModal(record?.deviceManagerName, record?.deviceType);
            }}
          >
            {intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' })}
          </a>
          <a
            key="detail"
            onClick={() => {
              setReadonly(true);
              handleModalOpen(true);
              setCurrentRow(record);
              changeDeviceModal(record?.deviceManagerName, record?.deviceType);
            }}
          >
            {intl.formatMessage({ id: 'systemManagement.generalProcedure.detail' })}
          </a>
          <a key="delete" className="global-del-color" onClick={() => remove([record])}>
            {intl.formatMessage({ id: 'systemManagement.generalProcedure.delete' })}
          </a>
        </Space>
      ),
    });
  }

  const previewInfoProps = {
    readonly: true,
    labelCol: {
      flex: `0 0 110px`,
    },
    colProps: { md: 12 },
  };
  return (
    <div>
      <ProTable<API.StationDeviceReq, API.PageParams>
        headerTitle={false}
        actionRef={actionRef}
        rowKey="id"
        params={{
          stationId: id,
        }}
        request={getList}
        columns={columns}
        rowSelection={
          !disableEdit && {
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }
        }
        search={false}
        toolBarRender={false}
      />
      <ModalForm
        modalProps={{
          destroyOnClose: true,
        }}
        initialValues={{
          ...currentRow,
          deviceType: currentRow?.deviceType?.toString() ?? '3',
          pcsType: currentRow?.pcsType?.toString(),
        }}
        disabled={readonly}
        formRef={formRef}
        submitter={{
          render: (_, doms) => !readonly && <Space>{doms}</Space>,
        }}
        title={readonly ? '查看设备' : currentRow?.id ? '编辑设备' : '新增设备'}
        width="600px"
        colProps={{ md: 12 }}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          let success;
          value.stationId = id;
          if (currentRow?.id) {
            success = await handleEdit({ ...currentRow, ...value } as API.StationDeviceReq);
          } else {
            success = await handleAdd(value as API.StationDeviceReq);
          }
          if (success) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormRadio.Group
          label={intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.DeviceType' })}
          name="deviceType"
          colProps={{ md: 24 }}
          valueEnum={DEVICE_TYPE}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.deviceType' }),
            },
          ]}
          fieldProps={{
            onChange: () => {
              formRef?.current?.setFieldValue('deviceManagerId', undefined);
            },
          }}
        />
        <ProFormDigit
          label={intl.formatMessage({
            id: 'systemManagement.siteAdministrationMenu.NumberOfDevices',
          })}
          name="deviceCount"
          colProps={{ md: 24 }}
          rules={[
            {
              required: true,
              message: intl.formatMessage({ id: 'systemManagement.requiredFields.deviceQuantity' }),
            },
          ]}
          fieldProps={{
            min: 1,
            max: 100000,
          }}
        />
        <ProFormDependency name={['deviceType']}>
          {({ deviceType }) => {
            return (
              <ProFormSelect
                label={intl.formatMessage({
                  id: 'systemManagement.deviceManagementMenu.Devicemodel',
                })}
                name="deviceManagerId"
                colProps={{ md: 24 }}
                params={{
                  deviceType: deviceType,
                }}
                request={async () => {
                  if (deviceType) {
                    const result = await getDeviceList({
                      deviceType: deviceType,
                    });
                    return (result.data || []).map((item) => {
                      return {
                        label: item.deviceModelName,
                        value: item.deviceId,
                      };
                    });
                  }
                }}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({
                      id: 'systemManagement.requiredFields.deviceModel',
                    }),
                  },
                ]}
                onChange={(v, option) => {
                  changeDeviceModal(option.label, deviceType);
                }}
              />
            );
          }}
        </ProFormDependency>
        <ProFormDependency name={['deviceManagerId', 'deviceType']}>
          {({ deviceManagerId, deviceType }) => {
            return (
              deviceManagerId && (
                <Card title="设备信息预览" style={{ width: '100%' }}>
                  <Row>
                    {deviceType === '3' ? (
                      <ProFormText {...previewInfoProps} label="AC" name="ac" addonAfter="V" />
                    ) : null}
                    {deviceType === '1' || deviceType === '2' ? (
                      <ProFormText
                        {...previewInfoProps}
                        label={intl.formatMessage({
                          id: 'systemManagement.deviceManagementMenu.RatedCapacity',
                        })}
                        name="ratedCapacity"
                        addonAfter="kWh"
                      />
                    ) : null}
                    <ProFormText
                      {...previewInfoProps}
                      label={intl.formatMessage({
                        id: 'systemManagement.deviceManagementMenu.RatedPower',
                      })}
                      name="ratedPower"
                      addonAfter="kW"
                    />
                    {deviceType === '3' ? (
                      <ProFormRadio.Group
                        {...previewInfoProps}
                        label={intl.formatMessage({
                          id: 'systemManagement.deviceManagementMenu.type',
                        })}
                        name="pcsType"
                        valueEnum={PCS_TYPE}
                      />
                    ) : (
                      <ProFormRadio.Group
                        {...previewInfoProps}
                        label={intl.formatMessage({
                          id: 'systemManagement.deviceManagementMenu.type',
                        })}
                        name="type"
                        valueEnum={BATTERY_BOX_TYPE}
                      />
                    )}
                    <ProFormRadio.Group
                      {...previewInfoProps}
                      label={intl.formatMessage({
                        id: 'systemManagement.deviceManagementMenu.status',
                      })}
                      name="status"
                      options={[
                        {
                          label: intl.formatMessage({
                            id: 'systemManagement.generalProcedure.enable',
                          }),
                          value: true,
                        },
                        {
                          label: intl.formatMessage({
                            id: 'systemManagement.generalProcedure.disable',
                          }),
                          value: false,
                        },
                      ]}
                    />
                    {deviceType === '1' || deviceType === '2' ? (
                      <>
                        <ProFormDigit
                          {...previewInfoProps}
                          name="bmsNum"
                          label={intl.formatMessage({
                            id: 'systemManagement.deviceManagementMenu.stacksNumber',
                          })}
                        />
                        <ProFormDigit
                          {...previewInfoProps}
                          name="clusterPerBms"
                          label={intl.formatMessage({
                            id: 'systemManagement.supplementary.numberOfClustersInEachStack',
                          })}
                        />
                        <ProFormDigit
                          {...previewInfoProps}
                          name="bmuPerBms"
                          label={intl.formatMessage({
                            id: 'systemManagement.supplementary.numberOfModulesInEachCluster',
                          })}
                        />
                        <ProFormDigit
                          {...previewInfoProps}
                          name="cellPerBmu"
                          label={intl.formatMessage({
                            id: 'systemManagement.supplementary.numberOfCellsInEachModule',
                          })}
                        />
                      </>
                    ) : null}
                    <Flex style={{ width: '100%', marginInline: 4 }}>
                      <ProForm.Item
                        {...previewInfoProps}
                        label={intl.formatMessage({
                          id: 'systemManagement.deviceManagementMenu.deviceImages',
                        })}
                        name="pictureDir"
                        style={{ flex: 1 }}
                      >
                        <PreviewPic />
                      </ProForm.Item>
                    </Flex>
                  </Row>
                </Card>
              )
            );
          }}
        </ProFormDependency>
      </ModalForm>
    </div>
  );
};

export type ToolBarProps = {
  tableRef: React.MutableRefObject<null>;
};
const ToolBarRender: React.FC<ToolBarProps> = ({ tableRef }) => {
  const intl = useIntl();
  const props: UploadProps = {
    name: 'file',
    multiple: true,
    showUploadList: false,
    customRequest: (info) => tableRef?.current?.customRequest(info),
  };

  return (
    <>
      <HandleBtn
        handleType="add"
        key="add"
        onClick={() => {
          tableRef?.current?.add();
        }}
      >
        {intl.formatMessage({ id: 'systemManagement.generalProcedure.new' })}
      </HandleBtn>
      <Upload {...props} key="import">
        <HandleBtn handleType="import">
          {intl.formatMessage({ id: 'systemManagement.generalProcedure.import' })}
        </HandleBtn>
      </Upload>
      <HandleBtn handleType="export" key="export" onClick={() => tableRef?.current?.download()}>
        {intl.formatMessage({ id: 'systemManagement.generalProcedure.export' })}
      </HandleBtn>
      <HandleBtn
        onClick={() => {
          tableRef?.current?.remove();
        }}
        handleType="delete"
        key="delete"
      >
        {intl.formatMessage({ id: 'systemManagement.generalProcedure.batchDelete' })}
      </HandleBtn>
    </>
  );
};

export default forwardRef(Table);
export { ToolBarRender };
